﻿
package extremefx.browser {
	import flash.external.ExternalInterface;

	/**
	 * @author Marcelo Volmaro
	 */
	public final class BrowserUtils {
		private static var _objectId:String;
		
		/**
		 * Searches through the parent documents DOM for our specific flash object.
		 * When it finds it, it returns the flash objects id. 
		 * If no id is set on the object/embed tag, this function will assign one and returns that.
		 * 
		 * This function also creates a javascript hash called "browserUtilHash" 
		 * which makes retrieving the object node easier and more efficient for other scripts.
		 * 
		 */
		public static function getObjectId():String {
			if (!ExternalInterface.available) return null;
			
			var objID:String = ExternalInterface.objectID || _objectId;
			
			if (objID == null || objID == ""){
				var uniqueId:String = "swf"+(new Date().getTime())+"_"+int(Math.random()*100000);
				
				ExternalInterface.addCallback(uniqueId, ping);
				_objectId = ExternalInterface.call(_getObjectID, uniqueId);
				
			} else {
				_objectId = objID;
			}
			
			return _objectId;
		}
	
		private static function ping():Boolean {
			return true;
		}

		private static var _getObjectID:XML = <script><![CDATA[
function (_uniqueId) {
	if (!window["efx"]) efx = {};
	if (!window.efx["browserUtilHash"]) efx.browserUtilHash = {};
	
	var i, _node, _pong, _nodeId,
	_getAttr = function (_el){
		return _el.getAttribute("id") || (_el.attributes["id"] ? _el.attributes["id"].nodeValue : null);
	},
	
	_findNode = function(_nodes) {
		i = 0;
		
		while (_node = _nodes[i++]){
			try {
				_pong = _node[_uniqueId](); 
				if (!_getAttr(_node)) _node.setAttribute("id", _uniqueId);
				efx.browserUtilHash[_uniqueId] = _node;
				
				return _uniqueId;
			} catch (e) {}
		}
	};
	
	if (!(_nodeId = _findNode(document.getElementsByTagName("object")))) {
		_nodeId = _findNode(document.getElementsByTagName("embed"));
	}
	
	return _nodeId;
}
]]></script>;
	}
}
